<?php

namespace common\models\db;

use Yii;

/**
 * This is the model class for table "tbl_oplog".
 *
 * @property int $oplog_id
 * @property int $log_type
 * @property int $user_id 后台用户id
 * @property string $user_name
 * @property string $op_ip
 * @property string|null $op_type
 * @property string|null $op_desc
 * @property string $create_time 创建时间
 * @property string|null $update_time 更新时间
 */
class Oplog extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'tbl_oplog';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['log_type', 'user_id'], 'integer'],
            [['user_name'], 'required'],
            [['create_time', 'update_time'], 'safe'],
            [['user_name', 'op_type'], 'string', 'max' => 255],
            [['op_ip'], 'string', 'max' => 32],
            [['op_desc', 'content'], 'string'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'oplog_id' => 'Oplog ID',
            'log_type' => 'Log Type',
            'user_id' => 'User ID',
            'user_name' => 'User Name',
            'op_ip' => 'Op Ip',
            'op_type' => 'Op Type',
            'op_desc' => 'Op Desc',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
        ];
    }

    /**
     * @param $data
     */
    public static function opLog($data)
    {
        $model = new self();
        $model->setAttributes($data);
        $model->op_ip = self::getRealIp();
        $model->save();
    }

    private static function getRealIp()
    {
        $ip = FALSE;
        //客户端IP 或 NONE
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = FALSE;
            }
            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        //客户端IP 或 (最后一个)代理服务器 IP
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }
}
